import Vue from 'vue'
import VueRouter from 'vue-router'
// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store/index'
import util from '@/libs/util.js'

import ApiNode from '@/api/system.node'
import layoutHeaderAside from '@/layout/header-aside'
const _import = require('@/libs/util.import.' + process.env.NODE_ENV)

// 路由数据
import { frameInRoutes } from '@/router/routes'
import routes from './routes'

// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

// 导出路由 在 main.js 里使用
const router = new VueRouter({
  routes
})

// let routerFlag = false;

function checkToken() {
  var _this = this
  var token = util.cookies.get('Authorization');


  if (token && token !== 'undefined') return true;
  return false;
}

function parseTreeToMenu(list) {
  let lang = util.cookies.get('lang');
  var menu = [];

  if (!!list) {
    for (var i = 0; i < list.length; i++) {
      var node = list[i];

      // 菜单类型 & 启用状态
      if (node.status != 1) continue;
      if (node.type != 1) continue;

      var item = {
        path: node.url || node.routePath,
        title: lang == 'en' ? node.enTitle : node.title,
        icon: node.icon,
      };

      if (node.children) {
        item.children = parseTreeToMenu(node.children);
      }

      menu.push(item);
    }
  }

  return menu;
  // console.log(tree);
}

function parseRouter(list, routerList = []) {
  
  let lang = util.cookies.get('lang');

  if (!!list) {
    for (var i = 0; i < list.length; i++) {
      var node = list[i];

      // 非启用
      if (node.status != 1) continue;

      if (node.children) {
        parseRouter(node.children, routerList);
      }

      // 没有组件和路由
      if (!node.routeComponent) continue;
      if (!node.routePath) continue;

      try {
        var item = {
          path: node.routePath,
          name: node.routeName,
          component: _import(node.routeComponent),
          meta: {
            auth: true,
            title: lang == 'en' ? node.enTitle : node.title,
            cache: node.routeCache == 1,
          },
        };

        routerList.push(item);
      } catch (err) {
        try {

        } catch (error) {
          console.error(err);

        }
      }
    }
  }

  return routerList;
}

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
  // 确认已经加载多标签页数据 https://github.com/d2-projects/d2-admin/issues/201
  await store.dispatch('d2admin/page/isLoaded')
  // 确认已经加载组件尺寸设置 https://github.com/d2-projects/d2-admin/issues/198
  await store.dispatch('d2admin/size/isLoaded')

  // 进度条
  NProgress.start();

  if (to.matched.some(r => r.name == '404' || to.meta.auth == true)) {
    // 存在Token
    if (checkToken()) {

      //   在这里判断
      let info = {}
      try {
        info = store.state.d2admin.user.info
      } catch (error) {
        info = {}
      }
      //
      if (info.mch && info.mch.regStatus != 1) {
        //  注册状态0.待审 1.通过 2.驳回 3.禁用
        router.push({
          path: "/registerStart",
        });
        return false
      }

      // 检查动态路由是否已经加载
      if (!window.routerFlag) {

        // 通过token登录获取用户信息
        // try {
        //   await store.dispatch('d2admin/account/loginByToken', {}, {root: true});
        // } catch (err) {
        //   store.dispatch('d2admin/account/logout', {}, { root: true });
        //   NProgress.done();
        //   return;
        // }
        try {
          var tree = await ApiNode.tree({ limit: 1, page: 1 });
          // 设置侧栏菜单
          var menu = parseTreeToMenu(Object.copy(tree.tree));
          store.commit('d2admin/menu/asideSet', menu);
          // 添加路由
          var routerList = parseRouter(tree.tree);
          var myRoutes = [
            {
              path: '/',
              component: layoutHeaderAside,
              children: routerList,
            }
          ];

          router.addRoutes(myRoutes);

          // 左侧标签页
          store.commit('d2admin/page/init', [].concat(frameInRoutes, myRoutes))

          window.routerFlag = true;

          next({ path: to.path });
        } catch (err) {

          NProgress.done();

          // 需要修改密码
          if (err.code === 1005) {
            next({
              name: 'change-password',
              query: {
                redirect: to.fullPath,
              }
            });
          }
          else {
            store.dispatch('d2admin/account/logout', {}, { root: true });
          }

        }


      }
      else {
        next();
      }

    }
    else {

      // 未经登录
      NProgress.done();
      next({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
    }
  }
  else {
    next();
  }

})

router.afterEach(to => {
  // 进度条
  NProgress.done()
  // 多页控制 打开新的页面
  store.dispatch('d2admin/page/open', to)
  // 更改标题
  util.title(to.meta.title)
})

export default router
